# -*- coding: utf-8 -*-
'''
@File    :   crc_table_builder.py
@Time    :   2024/08/22 07:23:46
@Author  :   string
@Version :   1.0
@Desc    :   None
'''
import typing

from py_xcp_bridge.common.checksum import reverse_bits


def build_crc_table(poly:int, reflect_in:bool, reflect_out:bool) -> None:
    # print("Building CRC table..., parameters: poly=0x{:04X}, reflect_in={}, reflect_out={}".format(poly, reflect_in, reflect_out))
    crc_table = [0x0000] * 256
    # print(crc_table)
    length = 0
    
    
    for i in range(256):
        crc =  reverse_bits(i, 16) >> 8 if reflect_in else i
        
        for bit in range(16):
            if (crc & 0x8000):
                crc = (crc << 1) ^ poly
            else:
                crc = crc << 1
        crc_table[i] = reverse_bits(crc, 16) if reflect_out else crc
        crc_table[i] = crc_table[i] & 0xFFFF
    
    
    
    print("CRC table built.")
    print_index = 0
    for i in range(16):
        for j in range(16):
            print("0x{:04X},".format(crc_table[print_index]), end=" ")
            print_index += 1
        print()
        
        